package com.geeklei.media.ui.menu.popup;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.geeklei.media.ui.R;

import java.util.List;

/**
 * Created by leixun on 16/6/7.
 */
public class ListPopupWindow extends BaseMenuPopup implements AdapterView.OnItemClickListener {
    private PopupListAdapter mAdapter;
    private OnSourceSelectListener mListener;

    public interface OnSourceSelectListener {
        void onSourceSelect(int i, ItemWraper itemWraper);
    }

    public ListPopupWindow(Context context, PopupListAdapter popupListAdapter) {
        this(context, R.string.vp_select_video_source, popupListAdapter);
    }

    public ListPopupWindow(Context context, int i, PopupListAdapter popupListAdapter) {
        super(context);
        setTitle(context.getResources().getString(i));
        this.mAdapter = popupListAdapter;
        this.mListView.setAdapter(this.mAdapter);
        this.mListView.setOnItemClickListener(this);
        this.mListView.setVerticalScrollBarEnabled(false);
    }

    public void setSources(List<ItemWraper> list) {
        this.mAdapter.setGroup((List) list);
    }

    public void setCurrentSource(ItemWraper itemWraper) {
        this.mAdapter.setCurrentSource(itemWraper);
    }

    public void setCurrentSource(int index){
        this.mAdapter.setCurrentSource(index);
    }

    public ItemWraper getCurrentSource() {
        return this.mAdapter.getCurrentSource();
    }

    public List<ItemWraper> getSources() {
        return this.mAdapter.getGroup();
    }

    protected int getPopupWidth() {
        return getContext().getResources().getDimensionPixelSize(R.dimen.vp_selectsource_popup_width);
    }

    public void setOnSourceSelectListener(OnSourceSelectListener onSourceSelectListener) {
        this.mListener = onSourceSelectListener;
    }

    public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
        if (adapterView != null && (adapterView.getItemAtPosition(i) instanceof ItemWraper) && this.mListener != null) {
            this.mListener.onSourceSelect(i, (ItemWraper) adapterView.getItemAtPosition(i));
            mAdapter.setCurrentSource((ItemWraper) adapterView.getItemAtPosition(i));
        }
    }

    public void show(ViewGroup viewGroup) {
        super.show(viewGroup);
        if (this.mAdapter.getCurrentSource() != null) {
            for (int i = 0; i < this.mAdapter.getCount(); i++) {
                if (this.mAdapter.getCurrentSource().equals((ItemWraper) this.mAdapter.getItem(i))) {
                    this.mListView.setSelection(i);
                    return;
                }
            }
        }
    }
}